package com.codrim.cs.data.server.dao.interceptor;

import com.codrim.common.utils.json.JsonMapper;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.DefaultReflectorFactory;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.ReflectorFactory;
import org.apache.ibatis.reflection.factory.DefaultObjectFactory;
import org.apache.ibatis.reflection.factory.ObjectFactory;
import org.apache.ibatis.reflection.wrapper.DefaultObjectWrapperFactory;
import org.apache.ibatis.reflection.wrapper.ObjectWrapperFactory;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.text.DateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.regex.Pattern;

import static java.util.regex.Pattern.CASE_INSENSITIVE;

/**
 * 调整了实现方式,需最后一个参数是字符串,并且符合`exxxx`或者`wxxxx`格式
 *
 * @author jxlai 分时区插入
 */
@Intercepts({@Signature(args = {Connection.class, Integer.class}, method = "prepare", type = StatementHandler.class)})
public class ZoneTableInterceptor implements Interceptor {

    private static final ObjectFactory DEFAULT_OBJECT_FACTORY = new DefaultObjectFactory();
    private static final ObjectWrapperFactory DEFAULT_OBJECT_WRAPPER_FACTORY = new DefaultObjectWrapperFactory();
    private static final ReflectorFactory DEFAULT_REFLECTORFACTORY = new DefaultReflectorFactory();
    private static final String DEFAULT_ZONE = "e0000";
    private static final String DEFAULT_TIMEDIMESION = "day";
    private static final Logger log = LoggerFactory.getLogger(ZoneTableInterceptor.class);

    private static final Pattern ZONE_REPLACE_REGEX = Pattern.compile(" e0000_", CASE_INSENSITIVE);
    private static final Pattern TIMEDIMESION_REPLACE_REGEX = Pattern.compile("_day_", CASE_INSENSITIVE);

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        final StatementHandler statementHandler = (StatementHandler) invocation.getTarget();
        final MetaObject metaStatementHandler = MetaObject.forObject(
                statementHandler, DEFAULT_OBJECT_FACTORY,
                DEFAULT_OBJECT_WRAPPER_FACTORY, DEFAULT_REFLECTORFACTORY);
        String originalSql = (String) metaStatementHandler.getValue("delegate.boundSql.sql");
        Object parameterObject = metaStatementHandler.getValue("delegate.boundSql.parameterObject");
        if (parameterObject == null) {
            return invocation.proceed();
        }
        log.debug("original mybatis sql: {} and param is {}", originalSql);
        try {
            String zone = zone(parameterObject);
            String newSql = originalSql.replaceAll("[\\s]+", " ");
            if (StringUtils.isNotBlank(zone) && !zone.equalsIgnoreCase(DEFAULT_ZONE)) {
                newSql = ZONE_REPLACE_REGEX.matcher(newSql).replaceAll(" " + zone + "_");
            }
            String timeDimesion = timeDimesion(parameterObject);
            if (StringUtils.isNotBlank(timeDimesion) && !timeDimesion.equalsIgnoreCase(DEFAULT_TIMEDIMESION)) {
                newSql = TIMEDIMESION_REPLACE_REGEX.matcher(newSql).replaceAll("_" + timeDimesion + "_");
            }
            metaStatementHandler.setValue("delegate.boundSql.sql", newSql);
            log.info("new sql:{},param:{}", newSql, JsonMapper.nonEmptyMapper().toJson(parameterObject));
        } catch (Exception e) {
            log.error("error sql: {} and param is {}", originalSql, parameterObject, e);
            throw e;
        }
        return invocation.proceed();
    }

    private String zone(Object parameterObject) {
        if (parameterObject instanceof Map && ((Map) parameterObject).containsKey("sZone")) {
            return String.valueOf(((Map) parameterObject).get("sZone"));
        }
        return null;
    }

    private String timeDimesion(Object parameterObject) {
        if (parameterObject instanceof Map && ((Map) parameterObject).containsKey("timeDimesion")) {
            return String.valueOf(((Map) parameterObject).get("timeDimesion"));
        }
        return null;
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }

    public static String showSql(Configuration configuration, BoundSql boundSql) {
        Object parameterObject = boundSql.getParameterObject();
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        String sql = boundSql.getSql().replaceAll("[\\s]+", " ");
        if (parameterMappings.size() > 0 && parameterObject != null) {
            TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
            if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
                sql = sql.replaceFirst("\\?", getParameterValue(parameterObject));

            } else {
                MetaObject metaObject = configuration.newMetaObject(parameterObject);
                for (ParameterMapping parameterMapping : parameterMappings) {
                    String propertyName = parameterMapping.getProperty();
                    if (metaObject.hasGetter(propertyName)) {
                        Object obj = metaObject.getValue(propertyName);
                        sql = sql.replaceFirst("\\?", getParameterValue(obj));
                    } else if (boundSql.hasAdditionalParameter(propertyName)) {
                        Object obj = boundSql.getAdditionalParameter(propertyName);
                        sql = sql.replaceFirst("\\?", getParameterValue(obj));
                    }
                }
            }
        }
        return sql;
    }

    private static String getParameterValue(Object obj) {
        String value = null;
        if (obj instanceof String) {
            value = "'" + obj.toString() + "'";
        } else if (obj instanceof Date) {
            DateFormat formatter = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.CHINA);
            value = "'" + formatter.format(new Date()) + "'";
        } else {
            if (obj != null) {
                value = obj.toString();
            } else {
                value = "";
            }

        }
        return value;
    }

}
